<?php
/**
 * Created by PhpStorm.
 * User: dx
 * Date: 16/4/1
 * Time: 下午6:09
 */
$api_service_path = __DIR__ . "/../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();


//$date_line = date('Y-m-d');
$date_line = date("Y-m-d",strtotime("-2 day"));

//$date1 = date('Y-m-d');
//echo date('Y-m-d',strtotime("$date1 +2 day"));

$rs = DB::table('orders')
    ->whereIn('status',array(1011,1112))
    ->whereIn('order_source',array(10,11))
    ->select('book_time','book_hour','order_id','user_id','phone')
//    ->limit(5)
    ->orderBy('created_at','desc')
    ->get();
foreach($rs as $v){
    $_o=Orders::find($v->order_id);
    if($_o){
//        $hour  = explode('-',$v->book_hour);
        $book_time = $v->book_time;
        $coupon_order_info = CouponOrderInfo::where('order_id',$v->order_id)->orderBy('id', 'desc')->first();
        $coupon_code = isset($coupon_order_info)?$coupon_order_info->code:"";
        $flag=false;//该订单是否取消
        if(strtotime($book_time) <= strtotime($date_line)){
            $flag=true;
        }
        if($flag){//如果该订单取消 取消订单操作
            Log::info("order_cancel script cancel order :".$v->order_id);
            OrderFlows::timeline(1310, $v->order_id,1,'service');
            if ($coupon_code) {
                $coupon = DB::table("coupons")->where("received_user_id", $v->user_id)->where("code", $coupon_code)->first();//恢复该订单的 优惠券
                if ($coupon) {
                    DB::update("update coupons set status =2 ,use_time='0000-00-00 00:00:00' ,used_user_id = 0 where id=? limit 1", array($coupon->id));
                }
            }

            $_o->status = 1310;
            $_o->updated_at = Common::currentTimeString();
            $_o->save();

            $order_remark = new OrderRemark();
            $order_remark->order_id = $v->order_id;
            $order_remark->status = 1310; //系统自动取消
            $order_remark->remark = '取消订单：系统自动取消';
            $order_remark->user_type = 'system';
            $order_remark->user_id = 1;
            $order_remark->save();
            $_p=Users::find($v->user_id);

            if($_p){
                $place = $_o->place==1?'上门':'到店';
                Sms::send_message($_p->area,$_p->phone,'您预约的'.$place.'订单已取消，订单号：'.$_o->order_id.'，欢迎您再次使用养车壹号。详询400-633-1919。');
            }
        }
    }
}
